package com.szholly.plug.form.core;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.ObjectUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


import com.szholly.utils.spring.SpringBeanFactory;
import com.szholly.utils.util.JSONUtils;
import com.szholly.utils.util.StringUtils;
import com.szholly.data.common.util.ConvertCaptionUtils;
import com.szholly.data.common.util.JSONConvertUtils;
import com.szholly.data.general.IQueryMap;
import com.szholly.data.general.ITable;
import com.szholly.data.general.ITableFactory;
import com.szholly.data.general.PageInfo;
import com.szholly.data.general.QueryMap;
import com.szholly.data.general.RelationOption;
import com.szholly.data.general.RowBase;
import com.szholly.data.general.interceptor.DbEditType;
import com.szholly.plug.form.core.interceptor.FormEditInterceptorClass;
import com.szholly.plug.safe.entity.role.RoleInitHelper;

import net.sf.json.JSONObject;

@RestController
@RequestMapping("/android")
public class AndroidController {
	
	private String token= "android_token";
	
	/**
	 * 登录
	 * @param userName
	 * @param password
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/login")
    @ResponseBody
	public String login(String userName, String password)throws Exception{
		checkToken(token);
		JSONObject wjo = new JSONObject();
		wjo.put("C_USERNAME", userName);
		wjo.put("C_PWD", password);
		ITableFactory tableFactory = (ITableFactory) SpringBeanFactory.getBean("TableFactory");
		ITable pTable = tableFactory.openTable("safe_user");
		String where=JSONUtils.toJSONString(wjo);
		HashMap<String, Object> whereMap = JSONUtils.toBean(where, HashMap.class);
		IQueryMap queryMap = new QueryMap();
		queryMap.setWhereMap(whereMap);
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageIndex(1);
		pageInfo.setPageSize(100000);
		pageInfo.setRefreshRowCount(true);
		List<RowBase> rows = pTable.pageSelect(RowBase.class, queryMap, pageInfo);
		JSONObject jo = new JSONObject();
		if (rows != null && rows.size() > 0) {
			String uid=rows.get(0).getValue("C_USERNAME").toString();
			String uname=rows.get(0).getValue("C_USEREALNAME").toString();
			jo.put("UserName", uname);
			jo.put("UserID", uid);
		} else {
			jo.put("UserName", "");
			jo.put("UserID", "");
		}
		return JSONUtils.toJSONString(jo);
		//return "{\"UserName\":\"chenxu\",\"UserID\":\"chenxu\"}";
	}
	
	/**
	 * 数据保存
	 * @param token
	 * @param userID
	 * @param tableName
	 * @param row
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save")
    @ResponseBody
    public String save(String token, String userID, String tableName, String row) throws Exception{
		
		checkToken(token);
		
		tableName = tableName.toUpperCase();
		try {
			RowBase entity = JSONConvertUtils.convertToEntity(row);
			Object obj = entity.getValue("_IS_DOMAIN_TRUE");
			if (obj != null && obj.toString().toLowerCase().equals("true")) {
				return null;
			} else {
				return tableSave(tableName, entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
    }
	
	/**
	 * 删除数据，根据数据行
	 */
	@RequestMapping("/delete")
    @ResponseBody
	@SuppressWarnings("unchecked")
	public String delete(String token, String userID, String tableName, String where)
			throws Exception {
		
		checkToken(token);
		
		if (StringUtils.IsNullOrSpace(tableName)
				|| StringUtils.IsNullOrSpace(where)) {
			return "{\"result\":true}";
		}
		tableName = tableName.toUpperCase();

		// 数据对象
		HashMap<String, Object> whereMap = JSONUtils.toBean(where, HashMap.class);

		ITableFactory tableFactory = (ITableFactory) SpringBeanFactory
				.getBean("TableFactory");
		ITable pTable = tableFactory.openTable(tableName);

		pTable.startEditing();
		try {
			IQueryMap queryMap = new QueryMap();
			queryMap.setWhereMap(whereMap);
			pTable.delete(queryMap);
			pTable.stopEditing(true);
			return "{\"result\":true}";
		} catch (Exception e) {
			pTable.stopEditing(false);
			throw e;
		}
	}

	
	/**
	 * 根据分页条件获取数据行
	 * 
	 * @param tableName
	 *            数据表名
	 * @param query
	 *            查询条件，Map对象，Json格式
	 * @param order
	 *            排序条件，Map对象，Json格式
	 * @param pageSize
	 *            最大分页大小
	 * @param pageIndex
	 *            分页索引
	 * @return
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonGenerationException
	 */
	@RequestMapping("/pageSelect")
    @ResponseBody
	@SuppressWarnings("unchecked")
	public String pageSelect(String token, String userID, String tableName, String query, String order,
			int pageSize, int pageIndex) throws JsonGenerationException,
			JsonMappingException, IOException {
		
		checkToken(token);
		
		if (StringUtils.IsNullOrSpace(tableName)) {
			return "";
		}
		tableName = tableName.toUpperCase();

		// 获取查询条件
		HashMap<String, Object> whereMap = JSONUtils.toBean(query,
				HashMap.class);

		// 获取排序条件
		HashMap<String, Object> orderMap = JSONUtils.toBean(order,
				HashMap.class);

		ITableFactory tableFactory = (ITableFactory) SpringBeanFactory
				.getBean("TableFactory");
		ITable pTable = tableFactory.openTable(tableName);
		if(pTable==null){
			return "";
		}
		
		IQueryMap queryMap = new QueryMap();
		queryMap.setAddCaptionField(true);
		queryMap.setWhereMap(whereMap);
		queryMap.setOrderByMap(orderMap);
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageIndex(pageIndex);
		pageInfo.setPageSize(pageSize);
		pageInfo.setRefreshRowCount(true);

		List<RowBase> rows = pTable.pageSelect(RowBase.class, queryMap, pageInfo);
		if (rows != null && rows.size() >= 0) {
			return JSONUtils.toJSONString(rows);
		} else {
			return "";
		}
	}
	
	/**
	 * 
	 * @param tableName
	 * @param row
	 * @param childTables
	 * @return
	 */
	@RequestMapping("/getChild")
    @ResponseBody
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String getChild(String token, String userID, String tableName, String row, String childTables) throws JsonGenerationException, JsonMappingException, IOException {
		
		checkToken(token);
		
		if (StringUtils.IsNullOrSpace(tableName)
				|| StringUtils.IsNullOrSpace(row)
				|| StringUtils.IsNullOrSpace(childTables)) {
			return null;
		}
		
		tableName = tableName.toUpperCase();
		RowBase pRow = JSONUtils.toBean(row, RowBase.class); // 要加载的数据行
		Map<String, Map> childMap = JSONUtils.toBeanEx(childTables, Map.class); // 要加载的数据行

		ITableFactory tableFactory = (ITableFactory) SpringBeanFactory.getBean("TableFactory");
		ITable pTable = tableFactory.openTable(tableName);
		
		Set<String> childKeys = childMap.keySet();
		for(String cTable : childKeys){
			Map itemMap = childMap.get(cTable);
			
			HashMap<String, Object> orderByMap = null;
			if(itemMap.containsKey("orderObject")){
				orderByMap = (HashMap<String, Object>)itemMap.get("orderObject");
			}
			
			String otherTName = null;
			if(itemMap.containsKey("otherTName")){
				otherTName = itemMap.get("otherTName").toString();
			}
			
			HashMap<String, String> otherRelation = null;
			if(itemMap.containsKey("otherRelation")){
				otherRelation = (HashMap<String, String>)itemMap.get("otherRelation");
			}
			
			if(!StringUtils.IsNullOrEmpty(otherTName)
					&& !StringUtils.IsNullOrEmpty(otherRelation)){
				RelationOption.FillEntityChild(pTable, pRow, cTable, 
						otherTName, otherRelation, orderByMap, true);
			} else {
				RelationOption.FillEntityChild(pTable, pRow, cTable, orderByMap, true);
			}
		}

		HashMap<String, List<RowBase>> childValues = pRow.getChildValues();
		if (childValues == null || childValues.size() <= 0) {
			return null;
		} else {
			return JSONUtils.toJSONString(childValues);
		}
	}
	
	/**
	 * 根据用户名获取android下的权限标签
	 * @param token
	 * @param userID
	 * @return
	 */
	@RequestMapping("/getSecuritys")
    @ResponseBody
	public String getSecuritys(String token, String userID){
		checkToken(token);
		
		if (StringUtils.IsNullOrSpace(userID)) {
			//return null;
			return "[]";
		}
		
		List<String> list = RoleInitHelper.getFunctions(userID);
		if (list == null || list.size() <= 0) {
			//return null;
			return "[]";
		} else {
			return JSONUtils.toJSONString(list);
		}
	}
	
	private String tableSave(String tableName, RowBase entity) throws Exception {
		ITableFactory tableFactory = (ITableFactory) SpringBeanFactory
				.getBean("TableFactory");
		ITable pTable = tableFactory.openTable(tableName);

		String returnString = FormEditInterceptorClass.BeforeDbEditOptionEx(
				pTable, entity, DbEditType.Insert);
		if (StringUtils.IsNullOrSpace(returnString)) {
			pTable.startEditing();
			try {
				pTable.save(entity);

				// 再做一次字典转议
				ConvertCaptionUtils.convertCaptionField(pTable, entity);
				ObjectMapper mapper = new ObjectMapper();
				String userMapJson = mapper.writeValueAsString(entity);
				pTable.stopEditing(true);

				return userMapJson;
			} catch (Exception e) {
				pTable.stopEditing(false);
				throw e;
			}
		} else {
			return returnString;
		}
	}

	private void checkToken(String token){
		if(!ObjectUtils.equals(token, this.token)){
			throw new RuntimeException("认证错误！");
		}
	}
}
